// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.linqingying.gitcode.tasks

import com.intellij.openapi.project.Project
import com.linqingying.gitcode.api.GitCodeServerPath
import com.linqingying.gitcode.authentication.GCAccountsUtil
import com.linqingying.gitcode.authentication.GCLoginRequest
import com.linqingying.gitcode.authentication.ui.GCLoginModel
import com.linqingying.gitcode.exceptions.GitCodeParseException

private object GCRepositoryEditorKt {
  fun askToken(project: Project, host: String): String? {
    val server = tryParse(host) ?: return null

    val model = object : GCLoginModel {
      var token: String? = null

      override fun isAccountUnique(server: GitCodeServerPath, login: String): Boolean = true

      override suspend fun saveLogin(server: GitCodeServerPath, login: String, token: String) {
        this.token = token
      }
    }
    GCAccountsUtil.login(model, GCLoginRequest(server = server), project, null)
    return model.token
  }

  private fun tryParse(host: String): GitCodeServerPath? {
    return try {
      GitCodeServerPath.from(host)
    }
    catch (ignored: GitCodeParseException) {
      null
    }
  }
}
